// pages/package/shopDetail/address.js
var app = getApp(),
  that, carList;
Page({
  data: {
    // tab切换  
    currentTab: 1,
    dates: '请选择日期',
    custId: "",
    ordType: 1,

    money: '',
    numbers: '',

    goods: [],
    id: '',
    cart_list: [],
    zfwz: '微信支付',
    kqyue: !0,
    name: '',
    phone: '',
    mess: '',
    shopData: '',
    goodsPrice: '',
    freight: 0,
    userData: [],
    address: {},
    showModal: !1,
    ordId: '',
    ordPayType: '',
    vipUser: {},
    levelName: '',
    discount: '',
    qlq: !0,
    listarr: ["代金券", "折扣券"],
    activeIndex: 0,
    djq: null,
    zkq: null,
    activeradio: '',
    yhqnum: '',
    yhqfull: '',
    yhqname: '',
    yhqkdje: '',
    kdje: '',
    totalprice: '',
    couponId: '',
    vipLevelInfo: null,
    balance: '',
    bizUserInfo: null,
    adId: '',
    disable: true,
    kdje: ''
  },
  submintInfo: function() {
    console.log(this.data.currentTab)
    if (this.data.currentTab == 1) {
      this.orderInfo()
    } else {
      this.deliveryInfo()
    }
  },
  orderInfo: function(e) {
    console.log(this.data.name)
    console.log(this.data.phone)
    if (this.data.name == null || this.data.name == "") {
      console.log('姓名')
      wx.showModal({
        title: "提示",
        content: "请输入收货人姓名"
      })
    } else if (this.data.phone == null || this.data.phone == "") {
      return wx.showModal({
        title: "提示",
        content: "请输入联系电话"
      })
    } else if (this.data.dates == '请选择日期' || this.data.dates == null || this.data.dates == '') {
      return wx.showModal({
        title: "提示",
        content: "请选择日期"
      })
    } else if (this.data.name && this.data.phone) {
      this.setData({
        showModal: !0
      })
    }
  },
  deliveryInfo: function() {
    console.log(that.cart_list)
    console.log(that.data.address)
    if (this.data.address == null && this.data.address == "") {
      wx.showModal({
        title: '提示',
        content: '请选择收货地址',
      }, !1)
    } else {

      this.setData({
        showModal: !0
      })

      that = this

    }
  },
  keyName: function(t) {
    console.log(t)
    this.setData({
      name: t.detail.value
    })
  },
  keyPhone: function(t) {
    console.log(t)
    this.setData({
      phone: t.detail.value
    })
  },
  keyMess: function(t) {
    this.setData({
      mess: t.detail.value
    })
  },
  swichNav: function(e) {
    console.log(e);
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
      })
    }
  },
  swiperChange: function(e) {
    console.log(e);
    this.setData({
      currentTab: e.detail.current,
    })

  },
  // 优惠券弹窗
  qlq: function() {
    console.log(this.data), this.setData({
      qlq: !1
    });
  },
  qdzz: function() {
    this.setData({
      qlq: !0
    });
  },
  tabClick: function(t) {
    var e = t.currentTarget.id;
    console.log(e), this.setData({
      activeIndex: t.currentTarget.id
    });
  },
  // 获取优惠券信息
  lqyhq: function(t, e) {
    var that = this;
    app.getData({
      url: app.api.getWdkq(),
      method: 'GET',
      data: {
        status: 1,
        memberId: that.data.id,
        companyId: wx.getStorageSync('companyId')
      },
      ok: res => {
        console.log(res)
        if (res.statusCode == 200 && res.errMsg == 'request:ok') {
          if (res.data.code == 1) {
            console.log("优惠券信息", res.data.data);
            for (var cd = res.data.data, djq = [], zkq = [], i = 0; i < cd.length; i++) {
              cd[i].couponType == 1 ? djq.push(cd[i]) : zkq.push(cd[i])
            }
            console.log(djq, zkq)
            that.setData({
              djq: djq,
              zkq: zkq
            })
          }
        }
      }
    })
  },
  radioChange: function(t) {
    this.setData({
      radioChange: t.detail.value
    }), console.log("radio发生change事件，携带value值为：", t.detail.value);
  },
  xzq: function(t) {
    console.log(t)
    if (wx.getStorageSync('vipLevelInfo') == null || wx.getStorageSync('vipLevelInfo') == '') {
      var dis = 1
    } else {
      var dis = wx.getStorageSync('vipLevelInfo').levelRebate * 0.01
    }
    console.log(dis)
    if (console.log(t.currentTarget.dataset, this.data.goodsPrice), Number(t.currentTarget.dataset.coupon) > this.data.goodsPrice) return wx.showModal({
      title: "提示",
      content: "您的商品小计金额不满足此优惠券条件"
    }), !1;
    this.setData({
      conponId: t.currentTarget.dataset.rdid,
      disable: false
    })
    if ("代金券" == t.currentTarget.dataset.type) {
      this.setData({
        kdje: t.currentTarget.dataset.full
      })
    };
    if ("折扣券" == t.currentTarget.dataset.type) {
      console.log(((1 - 0.1 * Number(t.currentTarget.dataset.full) * dis) * this.data.goodsPrice).toFixed(2))
      this.setData({
        kdje: ((1 - 0.1 * Number(t.currentTarget.dataset.full) * dis) * Number(this.data.goodsPrice)).toFixed(2)
      })
    };
    this.setData({
      couponId: t.currentTarget.dataset.rdid
    });
    this.gettotalprice();
  },
  //  点击日期组件确定事件  
  bindDateChange: function(e) {
    console.log(e.detail.value)
    this.setData({
      dates: e.detail.value
    })
  },
  yczz: function() {
    console.log(123)
    this.setData({
      showModal: !1
    });
  },
  // 获取总金额
  gettotalprice: function() {
    var t = this.data.freight, //运费  0
      e = this.data.goodsPrice, //商品小计  20
      a = this.data.discount, //折扣   95
      o = this.data.kdje; //优惠券   值
    console.log(t, e, a, o);

    var total;

    if (a) {
      total = e * 0.01 * a;
      console.log(total)
    } else {
      total = e
      console.log(total)
    }
    if (o) {
      total = total - o;
      console.log(total)
    } else {
      total = total
      console.log(total)
    }
    if (t) {
      total = total - t
      console.log(total)
    } else {
      total = total
      console.log(total)
    }
    total = parseInt(total).toFixed(2)
    console.log(total)
    this.setData({
      totalprice: total
    })
  },
  onLoad: function(options) {
    // 生命周期函数--监听页面加载
    this.cart_list = wx.getStorageSync("cart_list")
    console.log(this.data.cart_list);
  },
  onReady: function() {
    // 生命周期函数--监听页面初次渲染完成
  },
  onShow: function(e) {
    console.log(e)
    // 获取会员信息
    if (wx.getStorageSync("vipLevelInfo") == null || wx.getStorageSync("vipLevelInfo") == '') {
      vipLevelInfo = null
    } else {
      var vip = wx.getStorageSync("vipLevelInfo").levelRebate,
        vipLevelInfo = wx.getStorageSync('vipLevelInfo'),
        levelName = wx.getStorageSync("vipLevelInfo").levelName,
        discount = wx.getStorageSync("vipLevelInfo").levelRebate
      this.setData({
        levelName: levelName,
        discount: discount,
        vipLevelInfo: vipLevelInfo
      })
    }

    // 获取余额
    var bizUserInfo = wx.getStorageSync('bizUserInfo')
    this.setData({
      balance: wx.getStorageSync('bizUserInfo').balance,
      bizUserInfo: bizUserInfo
    })
    console.log(vip)
    // 获取门店信息
    var shopData = wx.getStorageSync('shopData')
    var id = wx.getStorageSync("bizUserInfo").id
    console.log(id)
    console.log(shopData)
    this.yczz()
    // 生命周期函数--监听页面显示
    that = this
    var e = wx.getStorageSync('cart_list')
    console.log(e)
    that.setData({
      id: id,
      goods: e,
      shopData: shopData,
      goodsPrice: (e.numbers * e.money).toFixed(2),
      money: e.money,
      numbers: e.numbers
    })
    this.getUserAddress()
    this.lqyhq(),
      this.gettotalprice()
  },
  // 获取用户地址
  getUserAddress: function() {
    var that = this,
      id = wx.getStorageSync("bizUserInfo").id
    console.log(that.data.adId)
    if (this.data.adId) {
      app.getData({
        url: app.api.selectUserAdd(),
        method: 'GET',
        data: {
          hyId: id,
          id: that.data.adId
        },
        ok: function(res) {
          console.log(res)
          if (res.data.list == null || res.data.list == '' || res.data.list.length == 0) {
            that.setData({
              address: null
            })
          } else {
            that.setData({
              custId: id,
              address: res.data.list[0]
            })
          }
        }
      })
    } else {
      app.getData({
        url: app.api.selectUserAdd(),
        method: 'GET',
        data: {
          hyId: id,
          isDefault: 1
        },
        ok: function(res) {
          console.log(res)
          if (res.data.list == null || res.data.list == '' || res.data.list.length == 0) {
            that.setData({
              address: null
            })
          } else {
            that.setData({
              custId: id,
              address: res.data.list[0]
            })
          }
        }
      })
    }
  },
  onHide: function() {
    // 生命周期函数--监听页面隐藏
  },
  onUnload: function() {
    // 生命周期函数--监听页面卸载
  },
  onPullDownRefresh: function() {
    // 页面相关事件处理函数--监听用户下拉动作
  },
  onReachBottom: function() {
    // 页面上拉触底事件的处理函数
  },
  onShareAppMessage: function() {
    // 用户点击右上角分享
    return {
      title: 'title', // 分享标题
      desc: 'desc', // 分享描述
      path: 'path' // 分享路径
    }
  },
  radioChange1: function(t) {
    console.log(t)
    console.log("radio1发生change事件，携带value值为：", t.detail.value), "wxzf" == t.detail.value && this.setData({
      zffs: 1,
      zfwz: "微信支付",
      btntype: "btn_ok1",
    }), "yezf" == t.detail.value && this.setData({
      zffs: 2,
      zfwz: "余额支付",
      btntype: "btn_ok2",
    }), "mdzf" == t.detail.value && this.setData({
      zffs: 3,
      zfwz: "门店支付",
      btntype: "btn_ok3",
    });
  },
  formSubmit: function(t) {
    app.getData({
      url: app.api.sendTemplateMsg(),
      method: 'POST',
      data: {
        "touser": wx.getStorageSync('openId'),
        template_id: 'aAkS5p136x7bLuYaC_r8OqYYB13QBzUCHRkSiBVI-JA',
        page: '',
        form_id: t.detail.formId,
        data: {
          "keyword1": {
            "value": that.data.ordId
          },
          "keyword2": {
            "value": '待发货'
          },
          "keyword3": {
            "value": that.data.totalprice
          },
          "keyword4": {
            "value": '2018-11-28'
          },
          "keyword5": {
            "value": that.cart_list.name
          }
        }
      },
      ok: function(res) {
        console.log(res)
      }
    })
    console.log(t.detail.formId)
    if (t.detail.value.radiogroup == "mdzf") {
      wx.showToast({
          title: '门店支付',
          duration: 800
        }),
        wx.removeStorageSync('cart_list'),
        app.getData({
          url: app.api.submitOrder(),
          method: 'POST',
          data: {
            custId: wx.getStorageSync('bizUserInfo').id,
            companyId: that.data.shopData.companyId,
            ordType: 1,
            totalOrdPrice: that.data.totalprice,
            totalOrdNum: that.cart_list.numbers,
            totalOrdAmt: that.data.totalprice,
            ordPayType: 3,
            custMess: that.data.mess,
            couponId: that.data.couponId,
            selfDate: that.data.dates + " 00:00:00",
            deliverType: that.data.currentTab,
            amt: that.data.totalprice,
            orderAddr: {
              rcverName: that.data.name,
              rcverMobile: that.data.phone,
              ordAddr1: '',
              ordAddr2: ''
            },
            orderGoodVoList: [{
              goodId: that.cart_list.good_id,
              goodNum: that.cart_list.numbers,
              stockId: ''
            }]
          },
          ok: function(res) {
            console.log(res)
          }
        })
      setTimeout(function() {
        wx.redirectTo({
          url: "../../../mine/pages/wddd/wddd"
        });
      }, 1000)
    }
    if (t.detail.value.radiogroup == "wxzf") {
      that = this
      if (that.data.address) {
        app.getData({
          url: app.api.submitOrder(),
          method: 'POST',
          data: {
            custId: that.data.custId,
            companyId: that.data.shopData.companyId,
            ordType: 1,
            totalOrdPrice: that.data.totalprice,
            totalOrdNum: that.cart_list.numbers,
            totalOrdAmt: that.data.totalprice,
            couponId: that.data.conponId,
            ordPayType: 1,
            custMess: that.data.mess,
            couponId: that.data.couponId,
            deliverType: that.data.currentTab,
            amt: that.data.totalprice,
            orderAddr: {
              rcverName: that.data.address.hyName,
              rcverMobile: that.data.address.telNumber,
              ordAddr1: that.data.address.provinceName,
              ordAddr2: that.data.address.detailInfo
            },
            orderGoodVoList: [{
              goodId: that.cart_list.good_id,
              goodNum: that.cart_list.numbers,
              stockId: that.cart_list.guigeId
            }]
          },
          ok: function(res) {
            that.data.ordId = res.data.data
            console.log(res.data.data)
            that.wxPay(res.data.data)
          }
        })
      }else{
        wx.showToast({
          title: '请选择收货地址',
          icon: "loading"
        })
      }
      // 提交订单

    }
    if (t.detail.value.radiogroup == "yezf") {
      if (this.data.currentTab == 1) {
        var z = wx.getStorageSync('bizUserInfo').balance,
          D = Number(this.data.totalprice);
        if (console.log(z, D), z < D) return void wx.showToast({
          title: "余额不足支付",
          icon: "loading"
        });
        app.getData({
          url: app.api.submitOrder(),
          method: 'POST',
          data: {
            custId: that.data.custId,
            companyId: that.data.shopData.companyId,
            ordType: 1,
            totalOrdPrice: that.data.totalprice,
            totalOrdNum: that.cart_list.numbers,
            totalOrdAmt: that.data.totalprice,
            couponId: that.data.conponId,
            ordPayType: 4,
            custMess: that.data.mess,
            selfDate: that.data.dates + " 00:00:00",
            couponId: that.data.couponId,
            deliverType: that.data.currentTab,
            balance: that.data.totalprice,
            orderAddr: {
              rcverName: that.data.name,
              rcverMobile: that.data.phone,
              ordAddr1: '',
              ordAddr2: ''
            },
            orderGoodVoList: [{
              goodId: that.cart_list.good_id,
              goodNum: that.cart_list.numbers,
              stockId: that.cart_list.guigeId
            }]
          },
          ok: function(res) {
            console.log(res)
            wx.showToast({
              title: "支付成功",
              duration: 800
            }), setTimeout(function() {
              wx.redirectTo({
                url: '../../../mine/pages/wddd/wddd?status=2',
              })
              that.getBizUserInfo()
            }, 1000);
          }
        })
      } else if (this.data.currentTab == 0) {
        var z = wx.getStorageSync('bizUserInfo').balance,
          D = Number(this.data.totalprice);
        if (console.log(z, D), z < D) return void wx.showToast({
          title: "余额不足支付",
          icon: "loading"
        });
        if (that.data.address) {
          app.getData({
            url: app.api.submitOrder(),
            method: 'POST',
            data: {
              custId: that.data.custId,
              companyId: that.data.shopData.companyId,
              ordType: 1,
              totalOrdPrice: that.data.totalprice,
              totalOrdNum: that.cart_list.numbers,
              totalOrdAmt: that.data.totalprice,
              couponId: that.data.conponId,
              ordPayType: 1,
              custMess: that.data.mess,
              couponId: that.data.couponId,
              deliverType: that.data.currentTab,
              amt: that.data.totalprice,
              orderAddr: {
                rcverName: that.data.address.hyName,
                rcverMobile: that.data.address.telNumber,
                ordAddr1: that.data.address.provinceName,
                ordAddr2: that.data.address.detailInfo
              },
              orderGoodVoList: [{
                goodId: that.cart_list.good_id,
                goodNum: that.cart_list.numbers,
                stockId: that.cart_list.guigeId
              }]
            },
            ok: function (res) {
              that.data.ordId = res.data.data
              console.log(res.data.data)
              that.wxPay(res.data.data)
            }
          })
        } else {
          wx.showToast({
            title: '请选择收货地址',
            icon: "loading"
          })
        }
      }
    }
  },
  getBizUserInfo: function() {
    var that = this
    app.getData({
      url: app.api.getBizUserInfo(),
      data: {
        openid: wx.getStorageSync('openId')
      },
      ok: function(res) {
        console.log(res)
        if (res.statusCode == 200 && res.errMsg == 'request:ok') {
          if (res.data.code == 1) {
            wx.setStorageSync('bizUserInfo', res.data.data)
          }
        }
      }
    })
  },

  wxPay: function(order) {
    // 确认支付
    app.getData({
      url: app.api.toPay(order, wx.getStorageSync('openId'), 1),
      method: 'GET',
      ok: function(e) {
        // var a=JSON.parse(t.data.params)
        console.log(e)
        wx.requestPayment({
          timeStamp: JSON.stringify((JSON.parse(e.data.params)).timeStamp),
          nonceStr: (JSON.parse(e.data.params)).nonceStr,
          package: (JSON.parse(e.data.params)).package,
          signType: 'MD5',
          paySign: (JSON.parse(e.data.params)).paySign,
          success: function(res) {
            console.log('-------------' + t.detail.formId + '------------')
            if (res.errMsg == 'requestPayment:ok') {

              app.getData({
                  url: app.api.setStatus(),
                  method: 'POST',
                  data: {
                    ordId: that.data.ordId,
                    payStatus: 1
                  }
                }),
                wx.showToast({
                  title: "支付成功",
                  duration: 800
                }), setTimeout(function() {
                  wx.redirectTo({
                    url: '../../../mine/pages/wddd/wddd',
                  })
                }, 1000);
            }
          },
          complete: function(res) {
            "requestPayment:fail cancel" == res.errMsg && wx.showToast({
              title: "取消支付",
              icon: "loading",
              duration: 800
            });
            setTimeout(function() {
              wx.redirectTo({
                url: '../../../mine/pages/wddd/wddd',
              })
            }, 1000);
          }
        })
      }
    })
  }
})